package com.xbxkj.api.app.mini.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbxkj.api.app.mini.config.wx.WxMaConfiguration;
import com.xbxkj.api.app.mini.entity.MiniAppConst;
import com.xbxkj.api.app.mini.request.bean.UserInfoModel;
import com.xbxkj.commen.bean.User;
import com.xbxkj.commen.controller.entity.ApiCode;
import com.xbxkj.commen.controller.helper.$;
import com.xbxkj.commen.controller.model.ApiResultModel;
import com.xbxkj.util.jwt.AuthSign;
import io.swagger.annotations.*;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author 张子艺
 * @packge com.xbxkj.api.app.mini.controller
 * @data 2019-12-31 10:31
 * @project HuaZhouDelivery
 */
@RestController
@RequestMapping("/app/mini/{appid}/user")
@Slf4j
@Api( tags="小程序登陆相关")
public class UserController extends MiniAppBaseController {


    @ApiOperation(value = "登陆接口", notes = "需要前端调用wx.login()获取code传入该接口中，接口会返回Token信息，后续所有接口进行请求时，都应在header中携带Token")
    @GetMapping(value = "/login")
    public ApiResultModel<Object> login(@PathVariable String appid, @RequestParam @ApiParam(name = "code", value = "调用wx.login()获取到的code", required = true) String code) {
        //多小程序
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        if (StrUtil.hasBlank(code)) {
            return $.error(ApiCode.parameter_error, "参数错误");
        }
        try {
            WxMaJscode2SessionResult result = wxService.jsCode2SessionInfo(code);
            String resultJSON = JSONObject.toJSONString(result);
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("openid",result.getOpenid());
            User  user= userService.getOne(queryWrapper);
            if(user==null){
                user=new User();
                user.setOpenid(result.getOpenid());
                userService.save(user);
            }
            String token = AuthSign.sign(user.getId());
            putCache(token, resultJSON);
            return $.success(ApiCode.success, ApiCode.success_msg, token);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return $.error("登陆失败");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return $.error("登陆失败");
        }
    }


    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @ApiOperation(value = "获取用户信息接口", notes = "获取用户信息")
    @GetMapping(value = "/info")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌" , paramType = "header", required = true),
            @ApiImplicitParam(name = "signature", value = "数据签名", paramType = "query", required = true),
            @ApiImplicitParam(name = "rawData", value = "微信用户基本信息", paramType = "query", required = true),
            @ApiImplicitParam(name = "encryptedData", value = "消息密文", paramType = "query", required = true),
            @ApiImplicitParam(name = "iv", value = "ivStr", paramType = "query", required = true)
    })
    public ApiResultModel<WxMaUserInfo> info(HttpServletRequest request, @PathVariable String appid, String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        String sessionKey=request.getAttribute(MiniAppConst.sessionKey).toString();
        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return $.error(ApiCode.login_time_out, "验证用户信息完整性失败");
        }
        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
         userService.addUser(userInfo);
        return $.success(userInfo);
    }

}